﻿// -----------------------------------------------------------------------
// <copyright file="RoleDto.cs" company="JSC Centido">
//  Copyright (c) JSC Centido. All rights reserved.
// </copyright>
// -----------------------------------------------------------------------

using System;
using System.Collections.Generic;
using System.Xml;
using System.Xml.Schema;

namespace Centido.Core.Dto
{
    /// <summary>
    ///   A data transfer object for a security role.
    /// </summary>
    public class RoleDto : DataTransferObject
    {
        /// <summary>
        ///   The name of the xml tag that is used to store this object.
        /// </summary>
        public const string XmlTag = "role";

        /// <summary>
        ///   The current xml schema version.
        /// </summary>
        public const string CurrentXmlSchemaVersion = "1";

        /// <summary>
        ///   The name of the xml attribute to store the security role name.
        /// </summary>
        public const string NameAttribute = "name";

        /// <summary>
        ///   The name of the xml attribute to store the security role display name
        /// </summary>
        public const string DisplayNameAttribute = "displayName";

        /// <summary>
        ///   The name of the xml tag to store the role users.
        /// </summary>
        public const string UserListTag = "users";

        /// <summary>
        ///   The name of the xml tag to store a role user.
        /// </summary>
        public const string UserTag = "user";

        /// <summary>
        ///   The name of the xml attribute to store the user name.
        /// </summary>
        public const string UserNameAttribute = "name";

        /// <summary>
        ///   The name of the xml tag to store the child role list.
        /// </summary>
        public const string ChildRoleListTag = "children";

        /// <summary>
        ///   The name of the xml tag to store a child role.
        /// </summary>
        public const string ChildRoleTag = "role";

        /// <summary>
        ///   The name of the xml attribute to store the child role name.
        /// </summary>
        public const string ChildRoleNameAttribute = "name";


        /// <summary>
        ///   The role users.
        /// </summary>
        private readonly List<string> _userList = new List<string>();

        /// <summary>
        ///   The child roles.
        /// </summary>
        private readonly List<string> _childRoleList = new List<string>();


        /// <summary>
        ///   Gets or sets the security role name.
        /// </summary>
        public string Name { get; set; }


        /// <summary>
        ///   Gets or sets the security role display name.
        /// </summary>
        public string DisplayName { get; set; }


        /// <summary>
        ///   Adds a security principal with the specified name to the role.
        /// </summary>
        /// <param name="principalName">The security principal name.</param>
        /// <exception cref="ArgumentNullException">Thrown when the value of <paramref name="principalName"/> is null.</exception>
        public void AddUser(string principalName)
        {
            if (principalName == null)
                throw new ArgumentNullException("principalName");

            if (!_userList.Contains(principalName))
                _userList.Add(principalName);
        }


        /// <summary>
        ///   Deletes a user with the specified name from the role users.
        /// </summary>
        /// <param name="userName">The user name.</param>
        /// <exception cref="ArgumentNullException">Thrown when the value of <paramref name="userName"/> is null.</exception>
        public void DeleteUser(string userName)
        {
            if (userName == null)
                throw new ArgumentNullException("userName");

            if (_userList.Contains(userName))
                _userList.Remove(userName);
        }


        /// <summary>
        ///   Gets the list of the role users.
        /// </summary>
        public ICollection<string> UserNames
        {
            get { return _userList; }
        }


        /// <summary>
        ///   Adds a security role with the specified name to the list of child roles.
        /// </summary>
        /// <param name="roleName">Thr role name.</param>
        /// <exception cref="ArgumentNullException">Thrown when the value of <paramref name="roleName"/> is null.</exception>
        public void AddChildRole(string roleName)
        {
            if (roleName == null)
                throw new ArgumentNullException("roleName");

            if (!_childRoleList.Contains(roleName))
                _childRoleList.Add(roleName);
        }


        /// <summary>
        ///   Removes a role with the specified name from the list of child roles.
        /// </summary>
        /// <param name="roleName">The role name.</param>
        /// <exception cref="ArgumentNullException">Thrown when the value of <paramref name="roleName"/> is null.</exception>
        public void DeleteChildRole(string roleName)
        {
            if (roleName == null)
                throw new ArgumentNullException("roleName");

            if (_childRoleList.Contains(roleName))
                _childRoleList.Remove(roleName);
        }


        /// <summary>
        ///   Gets the list of names of the child roles.
        /// </summary>
        public ICollection<string> ChildRoleNames
        {
            get { return _childRoleList; }
        }


        /// <summary>
        ///   This method is reserved and should not be used. When implementing the IXmlSerializable interface, you should return null (Nothing in Visual Basic) from this method, and instead, if specifying a custom schema is required, apply the <see cref="T:System.Xml.Serialization.XmlSchemaProviderAttribute"/> to the class.
        /// </summary>
        /// <returns>
        ///   An <see cref="T:System.Xml.Schema.XmlSchema"/> that describes the XML representation of the object that is produced by the <see cref="M:System.Xml.Serialization.IXmlSerializable.WriteXml(System.Xml.XmlWriter)"/> method and consumed by the <see cref="M:System.Xml.Serialization.IXmlSerializable.ReadXml(System.Xml.XmlReader)"/> method.
        /// </returns>
        public override XmlSchema GetSchema()
        {
            return null;
        }


        /// <summary>
        ///   Generates an object from its XML representation.
        /// </summary>
        /// <param name="reader">The <see cref="T:System.Xml.XmlReader"/> stream from which the object is deserialized. 
        /// </param>
        /// <exception cref="ArgumentNullException">Thrown when the value of <paramref name="reader"/> is null.</exception>
        public override void ReadXml(XmlReader reader)
        {
            if (reader == null)
                throw new ArgumentNullException("reader");

            reader.MoveToContent();

            // Reading the xml schema version
            var xmlSchemaVersion = ReadStringAttribute(reader, XmlSchemaVersionTag, isRequired: false);

            // If the xml schema version is not defined
            if (string.IsNullOrEmpty(xmlSchemaVersion)
                // or if it is the current xml schema version
                || xmlSchemaVersion == CurrentXmlSchemaVersion)
            {
                // Reading the role name
                Name = ReadStringAttribute(reader, NameAttribute);

                // Reading the role display name
                DisplayName = ReadStringAttribute(reader, DisplayNameAttribute, isRequired: false);

                // Clearing the user list
                _userList.Clear();

                // Clearing the child role list
                _childRoleList.Clear();

                var isEmptyElement = reader.IsEmptyElement;

                reader.ReadStartElement();

                if (!isEmptyElement)
                {
                    // If the role users are specified
                    while (reader.LocalName == UserListTag
                        // ... or the child roles are specified
                        || reader.LocalName == ChildRoleListTag)
                    {
                        isEmptyElement = reader.IsEmptyElement;

                        var currentTag = reader.LocalName;

                        reader.ReadStartElement();

                        if (isEmptyElement)
                            continue;
                        
                        switch (currentTag)
                        {
                            // If this a user list
                            case UserListTag:
                                while (reader.LocalName == UserTag)
                                {
                                    // Reading the user name
                                    AddUser(ReadStringAttribute(reader, UserNameAttribute));

                                    isEmptyElement = reader.IsEmptyElement;

                                    reader.ReadStartElement();

                                    if (!isEmptyElement) reader.ReadEndElement();
                                }
                                break;
                            // If this is a child role list
                            case ChildRoleListTag:
                                while (reader.LocalName == ChildRoleTag)
                                {
                                    // Reading the role name
                                    AddChildRole(ReadStringAttribute(reader, ChildRoleNameAttribute));

                                    isEmptyElement = reader.IsEmptyElement;

                                    reader.ReadStartElement();

                                    if (!isEmptyElement) reader.ReadEndElement();
                                }
                                break;
                        }

                        reader.ReadEndElement();
                    }

                    reader.ReadEndElement();
                }
            }
            else
                throw new ArgumentException(string.Format(
                    "The specified xml schema version is not supported (node = {0}, version = {1}).",
                    reader.Name,
                    xmlSchemaVersion));
        }


        /// <summary>
        ///   Converts an object into its XML representation.
        /// </summary>
        /// <param name="writer">The <see cref="T:System.Xml.XmlWriter"/> stream to which the object is serialized. 
        /// </param>
        /// <exception cref="ArgumentNullException">Trown when the value of <paramref name="writer"/> is null.</exception>
        public override void WriteXml(XmlWriter writer)
        {
            if (writer == null)
                throw new ArgumentNullException("writer");

            writer.WriteStartElement(XmlTag);

            // The xml schema version
            writer.WriteAttributeString(XmlSchemaVersionTag, CurrentXmlSchemaVersion);

            // The role name
            if (!string.IsNullOrEmpty(Name))
                writer.WriteAttributeString(NameAttribute, Name);

            // The role display name
            if (!string.IsNullOrEmpty(DisplayName))
                writer.WriteAttributeString(DisplayNameAttribute, DisplayName);

            // The role users
            if (_userList.Count > 0)
            {
                writer.WriteStartElement(UserListTag);

                foreach (var user in _userList)
                {
                    writer.WriteStartElement(UserTag);

                    // The user name
                    writer.WriteAttributeString(UserNameAttribute, user);

                    writer.WriteEndElement();
                }

                writer.WriteEndElement();
            }

            // The child roles
            if (_childRoleList.Count > 0)
            {
                writer.WriteStartElement(ChildRoleListTag);

                foreach (var childRole in _childRoleList)
                {
                    writer.WriteStartElement(ChildRoleTag);

                    // The child role name
                    writer.WriteAttributeString(ChildRoleNameAttribute, childRole);

                    writer.WriteEndElement();
                }

                writer.WriteEndElement();
            }

            writer.WriteEndElement();
        }


        /// <summary>
        ///   Copies the properties of the data transfer object to the
        /// specified role.
        /// </summary>
        /// <param name="role">The role.</param>
        /// <exception cref="ArgumentNullException">Thrown when the value of <paramref name="role"/> is null.</exception>
        public void CopyTo(Role role)
        {
            if (role == null)
                throw new ArgumentNullException("role");

            // The role display name
            if (DisplayName != role.DisplayName)
                role.DisplayName = DisplayName;
        }


        /// <summary>
        ///   Creates a data transfer object for the specified role.
        /// </summary>
        /// <param name="role">The specified role.</param>
        /// <exception cref="ArgumentNullException">Thrown when the value of <paramref name="role"/> is null.</exception>
        /// <returns>Returns the data transfer object for the specified security role.</returns>
        public static RoleDto CreateFrom(Role role)
        {
            if (role == null)
                throw new ArgumentNullException("role");

            var roleDto = new RoleDto
            {
                Name = role.Name,
                DisplayName = role.DisplayName
            };

            return roleDto;
        }
    }
}
